package service

import (
	"context"
	"gorm.io/gorm"
	"shop-bean/model"
	"shop-common/library/variables"
	"shop-common/utils/pagehelper"
	"shop-service/repository"
)

type IPickAddrService interface {
	FindPage(ctx context.Context, paginator *pagehelper.Paginator) (*pagehelper.Record, error)
	Create(ctx context.Context, addr *model.PickAddr) error
	Updates(ctx context.Context, id uint, addr *model.PickAddr) error
	DeleteBatch(ctx context.Context, ids []uint) error
}

func NewPickAddrService(repository repository.IPickAddrRepository) *PickAddrService {
	return &PickAddrService{variables.GormDB(), repository}
}

type PickAddrService struct {
	db         *gorm.DB
	repository repository.IPickAddrRepository
}

func (s *PickAddrService) FindPage(ctx context.Context, paginator *pagehelper.Paginator) (*pagehelper.Record, error) {
	count, err := s.repository.Count(s.db, paginator.Params)
	if err != nil {
		variables.Logger.Errorf(ctx, "find pickAddr to count failed: err %v, params %+v", err, paginator.Params)
		return paginator.Record, err
	}

	if count == 0 {
		return paginator.Record, nil
	}

	page, err := s.repository.FindPage(s.db, paginator.Params)
	if err != nil {
		variables.Logger.Errorf(ctx, "find pickAddr to page: err: %v, params %+v", err, paginator.Params)
		return paginator.Record, err
	}
	paginator.Count(count).Record.List = page
	return paginator.Record, nil
}

func (s *PickAddrService) Updates(ctx context.Context, id uint, addr *model.PickAddr) error {
	if err := s.repository.Updates(s.db, id, addr); err != nil {
		variables.Logger.Errorf(ctx, "updates where id pickAddr failed: err %v, id %d, columns %+v", err, id, addr)
		return err
	}
	return nil
}

func (s *PickAddrService) Create(ctx context.Context, addr *model.PickAddr) error {
	if err := s.repository.Create(s.db, addr); err != nil {
		variables.Logger.Errorf(ctx, "create pickAddr failed: err %v, addr %+v", err, addr)
		return err
	}
	return nil
}

func (s *PickAddrService) DeleteBatch(ctx context.Context, ids []uint) error {
	return s.db.Transaction(func(tx *gorm.DB) error {
		if err := s.repository.DeleteBatch(tx, ids); err != nil {
			variables.Logger.Errorf(ctx, "deleteBatch pickAddr failed: err %v, ids: %s", err, ids)
			return err
		}

		return nil
	})
}
